// Created by carolsail

import { ENUM_STATUS } from '../GbzEnum';
import { random } from '../GbzUtils';

const DATA_STORAGE_KEY = 'CC2_SCREWBOX'

const DATA_TIMERS = 600 //185

export default class GbzDataManager {

    private static _ins: any = null

    static getIns<T>(): T {
        if (this._ins === null) {
            this._ins = new GbzDataManager()
        }

        return this._ins
    }

    static get ins() {
        return this.getIns<GbzDataManager>()
    }

    status: ENUM_STATUS = ENUM_STATUS.UNRUN
    loading_rate: number = 0

    game_music: boolean = true
    game_sound: boolean = true

    game_level: number = 1
    game_level_current: number = 1
    game_level_max: number = 20


    data_timer: number = DATA_TIMERS
    data_revive_time: number = 60
    data_time_count: number = 0

    skillIndex: number = 0
    isSkill: boolean = false

    score: number = 0
    scoreMax: number = 0

    reset() {
        this.status = ENUM_STATUS.UNRUN
        this.data_timer = DATA_TIMERS
        this.data_time_count = 0
        this.isSkill = false
    }

    store() {
        cc.sys.localStorage.setItem(DATA_STORAGE_KEY, JSON.stringify({
            game_music: this.game_music,
            game_sound: this.game_sound,
            game_level: this.game_level,
            score: this.score,
            scoreMax: this.scoreMax
        }))
    }

    restore() {
        const _data = cc.sys.localStorage.getItem(DATA_STORAGE_KEY) as any
        try {
            const data = JSON.parse(_data)
            this.game_music = data?.game_music === false ? false : true
            this.game_sound = data?.game_sound === false ? false : true
            this.game_level = typeof data.game_level == 'number' ? data.game_level : 1
            this.score = typeof data.score == 'number' ? data.score : 0
            this.scoreMax = typeof data.scoreMax == 'number' ? data.scoreMax : 0
        } catch {
            this.game_music = true
            this.game_sound = true
            this.game_level = 2
            this.score = 0
            this.scoreMax = 0
        }

        this.game_level_current = this.game_level
        if (this.game_level_current > this.game_level_max) this.game_level_current = random(1, this.game_level_max)
    }
}
